import React, { useState } from 'react';
import { Form, Button, Input, Modal } from 'antd';

import { PasswordSetParam } from '../data.d';

export interface PasswordFormProps {
  onCancel: (flag?: boolean, formVals?: PasswordSetParam) => void;
  onSubmit: (values: PasswordSetParam) => void;
  passwordModalVisible: boolean;
  values: PasswordSetParam;
}
const FormItem = Form.Item;

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const PasswordForm: React.FC<PasswordFormProps> = (props) => {
  const [formValues, setFormValues] = useState<PasswordSetParam>({
    id: props.values.id,
    loginName: props.values.loginName,
    newPassword: props.values.newPassword,
  });

  const [form] = Form.useForm();

  const {
    onSubmit: handlePasswordSet,
    onCancel: handlePasswordSetModalVisible,
    passwordModalVisible,
  } = props;

  const handleRealSet = async () => {
    const fieldsValue = await form.validateFields();
    setFormValues({ ...formValues, ...fieldsValue });
    handlePasswordSet({ ...formValues, ...fieldsValue });
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => handlePasswordSetModalVisible(false)}>取消</Button>
        <Button type="primary" onClick={() => handleRealSet()}>修改</Button>
      </>
    );
  };

  return (
    <Modal
      width={640}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="重置密码"
      visible={passwordModalVisible}
      footer={renderFooter()}
      onCancel={() => handlePasswordSetModalVisible(false)}
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          id: formValues.id,
          loginName: formValues.loginName,
          newPassword: formValues.newPassword,
        }}
      >
        <FormItem
          name="id"
          label="id"
        >
          <Input disabled />
        </FormItem>
        <FormItem
          name="loginName"
          label="登陆用户"
        >
          <Input disabled />
        </FormItem>
        <FormItem
          name="newPassword"
          label="新密码"
        >
          <Input />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default PasswordForm;
